package com.dc.web.controller;


import com.dc.constant.MessageConstant;
import com.dc.dao.DepartmentDao;
import com.dc.dao.MaterialMachineDao;
import com.dc.dao.MaterialSolidDao;
import com.dc.dao.ShipRepairDao;
import com.dc.entity.*;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.PageShipRepairListBody;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Optional;

@Api(tags = "单船物量")
@RestController
@RequestMapping("/api/material")
@Slf4j
public class MaterialController {

    @Resource
    ShipRepairDao shipRepairDao;

    @Resource
    MaterialMachineDao materialMachineDao;

    @Resource
    MaterialSolidDao materialSolidDao;

    @Resource
    DepartmentDao departmentDao;

    ////////////////////////////////////////////////////////// machine
    @GetMapping("/machine/list")
    public AjaxResult listMachines(PageShipRepairListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize, Sort.by(Sort.Direction.DESC, "id"));

        ShipRepairEntity entity = new ShipRepairEntity();
        entity.setId(body.getShipRepairId());

        Page<MaterialMachineEntity> all = null;

        if(ObjectUtils.isNotEmpty(body.getDepartId())) {
            DepartmentEntity department = new DepartmentEntity();
            department.setId(body.getDepartId());
            all = materialMachineDao.findByShipRepairEntityAndDepartment(entity, department, pageRequest);
        } else {
            all = materialMachineDao.findByShipRepairEntity(entity, pageRequest);
        }

        all.getContent().forEach(t-> {
            t.setDepartId(t.getDepartment().getId());
            t.setShipRepairId(t.getShipRepairEntity().getId());
        });

        return AjaxResult.success(all);
    }

    @GetMapping("/machine/{id}")
    public AjaxResult showMachine(@PathVariable("id") Long id) {
        Optional<MaterialMachineEntity> optional = materialMachineDao.findById(id);
        if (!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_MATERIAL_MISSING);
        }
        MaterialMachineEntity entity = optional.get();
        entity.setShipRepairId(entity.getShipRepairEntity().getId());
        entity.setDepartId(entity.getDepartment().getId());
        return AjaxResult.success(entity);
    }

    @PostMapping("/machine")
    public AjaxResult addMachine(@RequestBody MaterialMachineEntity entity) {

        entity.setId(null);

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(entity.getShipRepairId());
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Optional<DepartmentEntity> optionalDepartment = departmentDao.findById(entity.getDepartId());
        if(!optionalDepartment.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_DEPARTMENT_MISSING);
        }
        DepartmentEntity departmentEntity = optionalDepartment.get();

        entity.setDepartment(departmentEntity);
        entity.setShipRepairEntity(shipRepairEntity);

        MaterialMachineEntity save = materialMachineDao.save(entity);

        return AjaxResult.success(save);
    }

    @PutMapping("/machine/{id}")
    public AjaxResult updateMachine(@PathVariable("id") Long id, @RequestBody MaterialMachineEntity paramEntity) {

        Optional<MaterialMachineEntity> optionalMachine = materialMachineDao.findById(id);
        if(!optionalMachine.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_MATERIAL_MISSING);
        }
        MaterialMachineEntity dbEntity = optionalMachine.get();

        Long departId = paramEntity.getDepartId();
        Long shipRepairId = paramEntity.getShipRepairId();

        if(!dbEntity.getDepartment().getId().equals(departId)) {        // 部门不相等，则更新实体
            Optional<DepartmentEntity> optionalDepartment = departmentDao.findById(departId);
            if(!optionalDepartment.isPresent()) {
                throw new ServiceException(MessageConstant.ERR_DEPARTMENT_MISSING);
            }
            DepartmentEntity departmentEntity = optionalDepartment.get();
            dbEntity.setDepartment(departmentEntity);
        }

        if(!dbEntity.getShipRepairEntity().getId().equals(shipRepairId)) {  // 维修单更新，则更新实体
            Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
            if(!optionalShipRepair.isPresent()) {
                throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
            }
            ShipRepairEntity shipRepairEntity = optionalShipRepair.get();
            dbEntity.setShipRepairEntity(shipRepairEntity);
        }

        //////////// 更新字段
        dbEntity.setSupplierUnit(paramEntity.getSupplierUnit());
        dbEntity.setMachine(paramEntity.getMachine());
        dbEntity.setMachineCode(paramEntity.getMachineCode());
        dbEntity.setNum(paramEntity.getNum());
        dbEntity.setUnit(paramEntity.getUnit());
        dbEntity.setHours(paramEntity.getHours());
        ///////////


        MaterialMachineEntity save = materialMachineDao.save(dbEntity);
        save.setShipRepairId(shipRepairId);
        save.setDepartId(departId);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/machine/{id}")
    public AjaxResult deleteMachine(@PathVariable("id") Long id) {
        materialMachineDao.deleteById(id);
        return AjaxResult.success();
    }

    ///////////////////////////////////////////////////// solid
    @GetMapping("/solid/list")
    public AjaxResult listSolid(PageShipRepairListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        //PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize, Sort.by(Sort.Direction.DESC, "id"));
        ShipRepairEntity entity = new ShipRepairEntity();
        entity.setId(body.getShipRepairId());

        Page<MaterialSolidEntity> all = null;

        if(ObjectUtils.isNotEmpty(body.getDepartId())) {
            DepartmentEntity department = new DepartmentEntity();
            department.setId(body.getDepartId());
            all = materialSolidDao.findByShipRepairEntityAndDepartment(entity, department, pageRequest);
        } else {
            all = materialSolidDao.findByShipRepairEntity(entity, pageRequest);
        }

        all.getContent().forEach(t-> {
            t.setDepartId(t.getDepartment().getId());
            t.setShipRepairId(t.getShipRepairEntity().getId());
        });

        return AjaxResult.success(all);
    }

    @GetMapping("/solid/{id}")
    public AjaxResult showSolid(@PathVariable("id") Long id) {
        Optional<MaterialSolidEntity> optional = materialSolidDao.findById(id);
        if (!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_MATERIAL_MISSING);
        }
        MaterialSolidEntity entity = optional.get();
        entity.setShipRepairId(entity.getShipRepairEntity().getId());
        entity.setDepartId(entity.getDepartment().getId());
        return AjaxResult.success(entity);
    }

    @PostMapping("/solid")
    public AjaxResult addSolid(@RequestBody MaterialSolidEntity entity) {

        entity.setId(null);

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(entity.getShipRepairId());
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Optional<DepartmentEntity> optionalDepartment = departmentDao.findById(entity.getDepartId());
        if(!optionalDepartment.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_DEPARTMENT_MISSING);
        }
        DepartmentEntity departmentEntity = optionalDepartment.get();

        entity.setDepartment(departmentEntity);
        entity.setShipRepairEntity(shipRepairEntity);

        MaterialSolidEntity save = materialSolidDao.save(entity);

        return AjaxResult.success(save);
    }

    @PutMapping("/solid/{id}")
    public AjaxResult updateSolid(@PathVariable("id") Long id, @RequestBody MaterialSolidEntity paramEntity) {

        Optional<MaterialSolidEntity> optionalSolid = materialSolidDao.findById(id);
        if(!optionalSolid.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_MATERIAL_MISSING);
        }
        MaterialSolidEntity dbEntity = optionalSolid.get();

        Long departId = paramEntity.getDepartId();
        Long shipRepairId = paramEntity.getShipRepairId();

        if(!dbEntity.getDepartment().getId().equals(departId)) {        // 部门不相等，则更新实体
            Optional<DepartmentEntity> optionalDepartment = departmentDao.findById(departId);
            if(!optionalDepartment.isPresent()) {
                throw new ServiceException(MessageConstant.ERR_DEPARTMENT_MISSING);
            }
            DepartmentEntity departmentEntity = optionalDepartment.get();
            dbEntity.setDepartment(departmentEntity);
        }

        if(!dbEntity.getShipRepairEntity().getId().equals(shipRepairId)) {  // 维修单更新，则更新实体
            Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
            if(!optionalShipRepair.isPresent()) {
                throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
            }
            ShipRepairEntity shipRepairEntity = optionalShipRepair.get();
            dbEntity.setShipRepairEntity(shipRepairEntity);
        }

        //////////// 更新字段
        dbEntity.setSupplierUnit(paramEntity.getSupplierUnit());
        dbEntity.setPickingDepart(paramEntity.getPickingDepart());
        dbEntity.setTransactionType(paramEntity.getTransactionType());
        dbEntity.setProjectCode(paramEntity.getProjectCode());
        dbEntity.setProjectName(paramEntity.getProjectName());
        dbEntity.setMaterialCode(paramEntity.getMaterialCode());
        dbEntity.setMaterialName(paramEntity.getMaterialName());
        dbEntity.setMaterialGroup(paramEntity.getMaterialGroup());
        dbEntity.setShippedNum(paramEntity.getShippedNum());
        dbEntity.setUnit(paramEntity.getUnit());
        dbEntity.setUnitWeight(paramEntity.getUnitWeight());
        dbEntity.setTotalWeight(paramEntity.getTotalWeight());
        dbEntity.setBuyingCom(paramEntity.getBuyingCom());
        dbEntity.setSupplierCom(paramEntity.getSupplierCom());
        ///////////


        MaterialSolidEntity save = materialSolidDao.save(dbEntity);
        save.setShipRepairId(shipRepairId);
        save.setDepartId(departId);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/solid/{id}")
    public AjaxResult deleteSolid(@PathVariable("id") Long id) {
        materialSolidDao.deleteById(id);
        return AjaxResult.success();
    }


}
